import {message} from 'antd';
import { reqLogin, reqCaptcha } from './server';

export const STATUS = {
  LOGIN: 'login',
  NOLOGIN: 'nologin'
}

export const models = {
  name: 'user',
  model: {
    state: {
      status: STATUS.NOLOGIN,
      captcha: '',
      captchaKey: '',
      username: '',
      role: ''
    },
    reducers: { 
      setCaptcha(state, payload) {
        return {...state, captcha: payload.image, captchaKey: payload.key}
      },
      setLogin(state, payload) {
        
        return {...state, username: payload.name, role: payload.role, status: STATUS.LOGIN}
      }
    },
    effects: dispatch => {
      return {
        async login(params) {
          const {code, data, msg} = await reqLogin(params);
          if(code == 0) {
            for(let props in data){
              localStorage.setItem(props, data[props]);
            }
            localStorage.setItem('pass-key', data.token);
            dispatch.user.setLogin(data);
            message.success('登录成功');

          } else {
            message.error(msg);
          }
        },
        async getCaptcha() {
          const {data, code} = await reqCaptcha();
          
          if( code == 0) {
            dispatch.user.setCaptcha(data);
          }else {
            message.error('验证码请求失败');
          }
        }
      }
    }
  }
}